<template>
  <div  style="padding: 15px;">
    <vxe-toolbar id="warehouseLocationId" :custom="{storage: true}" export :refresh="{query: findList}">
      <template v-slot:buttons>
        <el-button @click="findList">查询</el-button>
        <!-- <el-button @click="funcCreateBatchTask">下发</el-button> -->
        <el-button v-bind:disabled="printFlag" @click="funcPrint">打印出库单</el-button>
        <el-button v-bind:disabled="printFlag" @click="batchOutbound">批量出库</el-button>
        <el-button v-bind:disabled="printFlag" @click="batchReviewOutbound">批量复核出库</el-button>
        <!-- <el-button v-bind:disabled="printFlag" @click="printExpressBill">打印面单</el-button> -->
      </template>
    </vxe-toolbar>
    <vxe-table
      ref="xTable"
      border
      resizable
      stripe
      highlight-current-row
      :align="allAlign"
      show-footer
      highlight-hover-row
      :export-config='{type:"csv"}'
      row-id="id"
      class="mytable-footer"
      height="700"
       :loading="loading"
      :data="tableData"
      :edit-config="{trigger: 'click', mode: 'row', showStatus: true}"
      sort-config.remote
      @sort-change="sortList"
      auto-resize
      :seq-config="{startIndex: listQuery.pageNum * listQuery.pageSize - listQuery.pageSize}"
    >
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <vxe-table-column type="checkbox" width="60"></vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="statusText" title="状态" min-width="140" show-header-overflow show-overflow :formatter="formatterStatus"/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="item in statusList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="taskStatus"
          title="任务状态"
          min-width="150"
          sortable
          :formatter="({ cellValue }) => getEnumsOrDict('dict', 'taskStatusList').get(cellValue)"
        />
        <template #header>
          <el-select v-model="listQuery.taskStatus" placeholder="请选择" clearable>
            <el-option
              v-for="item in getEnumsOrDict('enum', 'taskStatusList')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="recheckTaskStatus"
          title="复核任务状态"
          min-width="150"
          sortable
          :formatter="({ cellValue }) => getEnumsOrDict('dict', 'taskStatusList').get(cellValue)"
        />
        <template #header>
          <el-select v-model="listQuery.recheckTaskStatus" placeholder="请选择" clearable>
            <el-option
              v-for="item in getEnumsOrDict('enum', 'taskStatusList')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
      <vxe-table-column field="issue" title="是否下发" min-width="150" sortable show-header-overflow show-overflow :formatter="formatterIssue"/>
      <template v-slot:header="{ column }">
        <el-select v-model="listQuery.issue" placeholder="请选择" clearable>
          <el-option
            v-for="item in issueList"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </template>
    </vxe-table-column>
    <!-- <vxe-table-column>
        <vxe-table-column field="orderTag" title="订单标识" min-width="140" show-header-overflow show-overflow :formatter="formatterOrderTag"/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.orderTag" placeholder="请选择订单标识" clearable>
            <el-option
              v-for="item in orderTagList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column> -->
      <vxe-table-column>
        <vxe-table-column field="warehouseName" title="仓库" min-width="150" />
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.warehouseCode" placeholder="请输入所属仓库 " style="width:100%" clearable>
            <el-option
              v-for="item in warehouseData"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="shipmentName" title="入驻商" min-width="150" sortable />
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.shipmentName" clearable filterable placeholder="请选择入驻商">
            <el-option
              v-for="item in options"
              :key="item.partyCode"
              :label="item.userName"
              :value="item.userName">
            </el-option>
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="code" title="出库单号" min-width="200" sortable show-header-overflow show-overflow/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.code" placeholder="请输入出库单号" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="deliveryCode" title="来源单号" min-width="200" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.deliveryCode" placeholder="请输入来源单号" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="wavePickingCode" title="波次号" min-width="200" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.wavePickingCode" placeholder="请输入波次号" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="typeName" title="单据类型" min-width="200" />
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.type" placeholder="请选择单据类型" clearable>
            <el-option
              v-for="item in typeList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="createdName" title="创建人" min-width="150" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.createdName" placeholder="请输入创建人" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="gmtCreated" title="创建时间" min-width="400" sortable show-header-overflow show-overflow />
        <template v-slot:header="{ column }">
          <el-date-picker
            v-model="listQuery.gmtCreatedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"

            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'gmtCreated')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="modifiedName" title="修改人" min-width="150" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.modifiedName" placeholder="请输入修改人" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="gmtModified" title="修改时间" min-width="400" sortable />
        <template v-slot:header="{ column }">
          <el-date-picker
            v-model="listQuery.gmtModifiedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"

            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'gmtModified')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column title="操作" fixed="right" min-width="150">
        <template slot-scope="scope">
          <el-tooltip  effect="dark" content="复核" placement="top" v-if="scope.row.status == '0' || scope.row.status == '1'">
            <vxe-button type="text" @click="funcRecheck(scope.row.code, scope.row.wavePickingCode, scope.row.temporaryCode)">
              <i class="iconfont iconbaoguo" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip  effect="dark" content="确认出库" placement="top" v-if="scope.row.status == '2' || scope.row.status == '4'">
            <vxe-button type="text" @click="funOutboundCheck(scope.row.code)">
              <i class="iconfont iconbaoguo" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip  effect="dark" content="查看" placement="top">
            <vxe-button type="text" @click="funcDetail(scope.row.code, scope.row.wavePickingCode, scope.row.temporaryCode)">
              <i class="el-icon-document" />
            </vxe-button>
          </el-tooltip>
        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager
      :loading="loading"
      :current-page.sync="listQuery.pageNum"
      :page-size.sync="listQuery.pageSize"
      :total="listQuery.total"
      :page-sizes="[10, 20, 50, 100, 500, 1000]"
      :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
      @page-change="handlePageChange"
    />
    <vxe-modal v-model="modelPrintFlag" title="打印" width="900" height="800" destroy-on-close resize>
      <compPrint ref="printRef" :printData="printOutbound"  @fatherPrintMethod="fatherPrint"/>
    </vxe-modal>
    <vxe-modal v-model="printExpressBillmodel" title="打印面单" width="600" height="600" destroy-on-close>
      <printFaceSheet :printData="printData" @finshPrint="openClosePrintMode" />
    </vxe-modal>
  </div>
</template>
<script>
import Vue from 'vue'
import 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/index.css'
import XEUtils from 'xe-utils'
import VXEUtils from 'vxe-utils'
Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
import { getWarehouse} from '@/api/basicInfo'
import '@/assets/iconfont/iconfont.css';
import compPrint from './components/print.vue'
import printFaceSheet from '@/components/Printing'
import { outboundList, outboundCheck, printExpressOutbound, shipments, batchOutboundConfirm, batchReviewOutbound } from '@/api/outStorage'
import { createTask, createBatchTask } from '@/api/store'
export default {
  name: '出库单管理',
  components: {
    compPrint,
    printFaceSheet
  },
  data() {
    return {
      message: '',
      initFinishFlag: false,
      modelPrintFlag:false, //打印开关
      // 日期选项
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      loading: false,
      allAlign: 'center',
      tableData: [],
      modelAddFlag: false,
      warehouseData:[],
      statusList:[                       //状态
        { code: "0", name: "待复核" },
        { code: "1",name: "复核中" },
        { code: "2",name: "待出库" },
        { code: "3",name: "出库完成" },
        { code: "4",name: "部分出库" },
        { code: "5",name: "取消出库" },
      ],

      typeList: [
          { code: '0', name: '销售出库' },
          { code: '1', name: '报损出库' },
          { code: '2', name: '领用出库' },
          { code: '3', name: '盘亏出库' },
          { code: '4', name: '采购退货' },
          { code: '5', name: '调拨出库' },
      ],
      options: [],
      modelEditFlag: false,
      modelDetailFlag: false,
      copy: false,
      issueList: [
        {code: '0', name:'否'},
        {code: '1', name:'是'},
      ],
      orderTagList: [
        {code: '1', name:'单品单件'},
        {code: '2', name:'单品多件'},
        { code: '3', name: '多品' },
        { code: '4', name: '爆品' },
        { code: '5', name: '按单' }
      ],
      listQuery: {
        total: 0,             //总数
        createdByName:'',         //创建人
        modifiedByName:'',        //修改人
        gmtCreated:'',        //创建时间
        gmtModified:'',       //修改时间
        code:'',                                    //出库单号 ,
        remarks:'',                                 //备注 ,
        shipmentName:'',                            //入驻商 ,
        deliveryCode:'',                              //来源单号 ,
        wavePickingCode:"", // 波次号
        status:'3',                                  //状态 ,
        warehouseCode:'',                           //仓库
        pageNum: 1,
        pageSize: 10,
        sortField: '',
        sortType: '',
        issue: '',
        socket: null
      },
      printOutbound: [], // 要打印出库单的数据
      printData: [], // 要打印的面单数据
      printExpressBillmodel: false, //打印机组件
      needLoadList: false, // 在keep-live钩子函数activated内是否需要加载列表
    }
  },
  created() {
    this.$eventBus.$on("refreshList", () => {
      this.findList()
    })
    this.getWarehouse()
  },
  computed: {
    'printFlag': function() {
      if(this.initFinishFlag) {
        let selectRecords = this.$refs.xTable.getCheckboxRecords();
        if(selectRecords.length > 0) {
          return false;
        } else {
          return true;
        }
      }
      return true;
    },
  },
  activated() {
    const { meta: { noCache } } = this.$route
    if (!noCache && this.needLoadList) this.findList()
  },
  methods: {
    // 打印组件的父方法
    fatherPrint() {
      this.modelPrintFlag = false
      this.findList()
    },
    //打印
    funcPrint() {
      let selectRecords = this.$refs.xTable.getCheckboxRecords()
      let arr = []
      selectRecords.forEach( i => {
        arr.push(i.code)
      })
      this.printOutbound = arr
      this.modelPrintFlag = true
    },
    openClosePrintMode() {
      this.printExpressBillmodel = !this.printExpressBillmodel
    },
    // 打印面单
    printExpressBill() {
      let selectRecords = this.$refs.xTable.getCheckboxRecords();
      let arr = [];
      selectRecords.forEach((i) => {
        arr.push(i.code);
      });
      printExpressOutbound(arr.join(',')).then(res => {
        if (res.status === 0) {
          if (res.data.length>0) {
            this.printData = res.data
            this.openClosePrintMode()
          } else {
            this.$message.warning('没有打印数据不可打印！')
          }
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    formatterIssue({cellValue}){
      if(cellValue == '0'){
        return '否'
      }else if(cellValue == '1'){
        return  '是'
      }
      return cellValue
    },
    formatterOrderTag({ row, cellValue }) {
      let val = row.orderTag;
      this.orderTagList.forEach(e=>{
        if(row.orderTag == e.code){
          val =  e.name;
          return;
        }
      })
      return val;
    },
    changeDate(value, prefix) {
      if (value) {
        this.listQuery[`${prefix}Start`] = value[0] + " 00:00:00";
        this.listQuery[`${prefix}End`] = value[1] + " 23:59:59";
      } else {
        this.listQuery[`${prefix}Start`] = "";
        this.listQuery[`${prefix}End`] = "";
      }
    },
    //仓库查询
    getWarehouse(){
      getWarehouse().then(response => {
        this.warehouseData = response.data
        this.findList()
        this.initFinishFlag = true;
      })
    },

    // 跳转到复核页面
    funcRecheck(code, wavePickingCode, temporaryCode) {
      let  path = '/wms/recheck'
      // if (temporaryCode) {
      //   path = '/wms/outWaveNumberCheck'
      // } else {
      //   path = '/wms/recheck'
      // }
      // const path = wavePickingCode ? '/wms/outWaveNumberCheck' : '/wms/recheck'
      this.$router.push({
        path,
        query: { code: code, wavePickingCode}
      });
    },

    //确认出库
    funOutboundCheck(code){
      this.$confirm('确认出库吗？').then(_ => {
        const rLoading = this.openLoading('确认出库...')
        outboundCheck(code).then(response => {
          if(response.status === 0 && !response.data){
            this.$message({ dangerouslyUseHTMLString: true, message: response.msg, type: 'success' })
          }else {
            if(response.data.status !== 0){
              this.$message({ dangerouslyUseHTMLString: true, message: response.data.msg, type: 'error' })
            }
          }
        }).finally(() => {
          this.findList()
          rLoading.close()
        })
      })
    },

    // 单个下发
    // funcCreateTask(code){
    //   let params = {
    //     taskType: 'CHECK',
    //     sourceCode: code
    //   }
    //   createTask(params).then((response)=>{
    //     this.$message({ dangerouslyUseHTMLString: true,message: response.msg, type: 'success'})
    //     this.findList()
    //   })
    // },

    // 批量下发
    funcCreateBatchTask(){
      let selectRecords = this.$refs.xTable.getCheckboxRecords()
      if(selectRecords.length == 0){
        this.$message.error("请选择要下发的单据!");
        return
      }
      let codes = []
      selectRecords.forEach( i => {
        codes.push(i.code)
      })

      let params = {
        taskType: 'CHECK',
        sourceCodes: codes
      }
      createBatchTask(params).then((response)=>{
        this.$message({ dangerouslyUseHTMLString: true,message: response.msg, type: 'success'})
        this.findList()
      })
    },
    // 批量出库
    batchOutbound(){
      const selectRecords = this.$refs.xTable.getCheckboxRecords()
      const forOutbound = selectRecords.some(item => item.status === '2')
      if(forOutbound){
        const codes = selectRecords.map(item => item.code)
        batchOutboundConfirm(codes).then((res)=>{
          this.$message.success(res.data)
        })
      } else {
        this.$message.error("请选择待出库的单据!")
      }
    },
    // 批量复核出库
    batchReviewOutbound() {
      const selectRecords = this.$refs.xTable.getCheckboxRecords()
      const forOutbound = selectRecords.some(item => item.status === '0')
      if(forOutbound){
        const codes = selectRecords.map(item => item.code)
        batchReviewOutbound(codes).then((res)=>{
          this.$message.success(res.data)
        })
      } else {
        this.$message.error("请选择待复核的单据!")
      }
    },
    // 翻译状态
    formatterStatus({ row, cellValue }) {
      let val = row.status;
      this.statusList.forEach(e=>{
        if(row.status == e.code){
          val =  e.name;
          return;
        }
      })
      return val;
    },

    //获取列表
    findList() {
      this.loading = true
      shipments().then(res => {
        this.options = res.data
      })
      return outboundList(this.listQuery).then(response => {
        this.tableData = response.data.records
        this.listQuery.total = response.data.total
        this.loading = false
      }).finally(()=> this.needLoadList = true)
    },
    // 排序
    sortList({ column, property, order }) {
      if (order) {
        this.listQuery.sortField = property
        this.listQuery.sortType = order
      } else {
        this.listQuery.sortField = ''
      }
      this.findList()
    },
    // 详情方法
    funcDetail(code, wavePickingCode, temporaryCode) {
      let path = '/wms/outboundDetail'
      // if (temporaryCode) {
      //   path = '/wms/outWaveNumber'
      // } else {
      //   path = '/wms/outboundDetail'
      // }

      // const path = wavePickingCode ? '/wms/outWaveNumber' : '/wms/outboundDetail'
      this.$router.push({
        path,
        query: { code: code, wavePickingCode}
      });
    },
    // 公共取消
    fatherCancel(modelFlag) {
      switch (modelFlag) {
        case 'add':
          this.modelAddFlag = false
          break
        case 'edit':
          this.modelEditFlag = false
          break
        case 'detail':
          this.modelDetailFlag = false
          break
        default:
      }
    },
    // 分页handle
    handlePageChange({ currentPage, pageSize }) {
      this.listQuery.pageNum = currentPage
      this.listQuery.pageSize = pageSize
      this.findList()
    },
    // 底部颜色设置
   /*  footerCellClassName({ $rowIndex, column, columnIndex }) {
      if (columnIndex === 0) {
        if ($rowIndex === 0) {
          return 'col-blue'
        } else {
          return 'col-red'
        }
      }
    }, */
    // 设置底部合计
    footerMethod({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return '合计'
          }
          if (['pageviews', 'forecast'].includes(column.property)) {
            return XEUtils.sum(data, column.property)
          }
          return null
        })
      ]
    }
  },
  destroyed() {
    this.$eventBus.$off('refreshList')
  },
}
</script>

<style>
.vxe-table .vxe-body--column:not(.col--ellipsis), .vxe-table .vxe-footer--column:not(.col--ellipsis), .vxe-table .vxe-header--column:not(.col--ellipsis) {
 padding: 6px 0;
}
.vxe-toolbar{padding:0 0 10px 0}
</style>
